import os
import platform
from python_checker import PythonChecker
from package_checker import PackageChecker

def get_system_info():
    system = platform.system()
    if system == "Windows":
        version = platform.win32_ver()[0]
        return f"Windows {version}"
    elif system == "Darwin":
        version = platform.mac_ver()[0]
        return f"macOS {version}"
    elif system == "Linux":
        try:
            with open('/etc/os-release') as f:
                for line in f:
                    if line.startswith('PRETTY_NAME='):
                        return line.split('=')[1].strip().strip('"')
        except:
            return f"Linux {platform.release()}"
    return system

def main():
    # 显示系统信息
    system_info = get_system_info()
    print(f"\n当前操作系统: {system_info}")
    print("-" * 60)

    # 询问用户排序方式
    while True:
        sort_choice = input("\n请选择排序方式:\n1. 按包名首字母顺序排序\n2. 按包大小从大到小排序\n请输入选项(1/2，默认1): ").strip()
        if sort_choice == "":
            sort_choice = "1"
        if sort_choice in ["1", "2"]:
            break
        print("输入无效，请重新选择")

    # 创建Python检查器实例
    python_checker = PythonChecker()
    # 获取所有Python版本及其路径
    python_versions = python_checker.get_python_versions()

    # 遍历每个Python版本
    for version, path in python_versions.items():
        print(f"\nPython {version} 已安装的包:")
        print("-" * 60)
        print(f"{'包名':<30} {'版本':<15} {'大小':<10}")
        print("-" * 60)
        
        # 创建软件包检查器实例
        package_checker = PackageChecker(path)
        # 获取已安装的软件包信息
        packages = package_checker.get_installed_packages()
        
        # 根据用户选择进行排序
        if sort_choice == "1":
            # 按包名字母顺序排序
            packages.sort(key=lambda x: x['name'].lower())
        else:
            # 按包大小从大到小排序，将"未知"大小的包放在最后
            def get_size_value(package):
                size = package['size']
                if size == "未知":
                    return -1
                try:
                    return float(size.split()[0])  # 提取MB值进行排序
                except:
                    return -1
            packages.sort(key=get_size_value, reverse=True)

        # 输出软件包信息
        for package in packages:
            print(f"{package['name']:<30} {package['version']:<15} {package['size']:<10}")

if __name__ == "__main__":
    main() 